package com.ocp.socket.server.mina;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @Auther: zhangzh
 * @Date: 2019/1/23 10:08
 * @Description:
 * @Version: 1.0.0
 */
public class MinaLongConnServer {

    private final static Logger log = LoggerFactory.getLogger(MinaLongConnServer.class);

    @Value("${sktPort}")
    private int sktPort;


    public void start() {

        IoAcceptor acceptor = new NioSocketAcceptor();

        //添加日志过滤
        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("myCodec", new ProtocolCodecFilter(new ByteArrayCodecFactory(Charset.forName("UTF-8"))));

        //设置回调监听
        acceptor.setHandler(new MinaLongConnServerHandler());
        //设置读取大小
        acceptor.getSessionConfig().setReadBufferSize(2048);
        //设置超时时间
//        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

        try{
            acceptor.bind(new InetSocketAddress(sktPort));
        } catch (BindException e) {
            log.info("端口使用中....");
            log.info("请关掉相关程序并重新运行服务器！");
            System.exit(0);
        } catch (IOException e) {
            log.error("启动失败：", e);
        }
    }

}
